package com.mgy.example.dao.config.db.sharding;

import io.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 基于sharding-jdbc的配置
 *
 * @author mgy
 */
//@Configuration
//@EnableAspectJAutoProxy(proxyTargetClass = true)
//@MapperScan(basePackages = "com.mgy.example.dao.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class ShardingJdbcMybatisConfig {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis.config-location}")
    private String configLocation;


    @Bean("yamlShardingJdbcDataSource")
    public DataSource getYamlShardingJdbcDataSource() throws IOException, SQLException {
        File yamlFile = new PathMatchingResourcePatternResolver().getResource("classpath:yaml/config-sharding-rule.yaml").getFile();
        Assert.notNull(yamlFile, "找不到文件sharding-rule.yaml");
        return YamlShardingDataSourceFactory.createDataSource(yamlFile);
    }

    /**
     * 需要手动配置事务管理器
     * sharding-jdbc
     */
    @Bean
    public DataSourceTransactionManager transactitonManager(@Qualifier("yamlShardingJdbcDataSource") DataSource yamlShardingJdbcDataSource) {
        return new DataSourceTransactionManager(yamlShardingJdbcDataSource);
    }

    /**
     * sharding-jdbc
     */
    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("yamlShardingJdbcDataSource") DataSource yamlShardingJdbcDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(yamlShardingJdbcDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource(configLocation));
        return bean.getObject();
    }


    @Bean
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
